package com.rectcircle.scalatrateset.controller

import com.rectcircle.scalatrateset.auth.AuthenticationSupport
import org.scalatra.Ok

/**
  * @author Rectcircle
  */
class LoginController extends ScalatratestStack with AuthenticationSupport{
	
	//验证是否记住登录
	before(){
		if(!isAuthenticated) { //如果没有运行记住密码
			scentry.authenticate("RememberMe") //执行这个策略
		}
	}
	
	get("/") {
		//如果记住登录，自动返回管理页面
		if (isAuthenticated) redirect("admin")
		//否则返回登录页面
		val html = """
	 	<html>
			<body>
				<p>Please login:</p>
				<form action="/login/handle" method="post">
					<p>
						<input type="text" name="username"/><br>
						<input type="password" name="password"/><br/>
						<label>Remember Me:</label><input type="checkbox" name="rememberMe" value="true" />
					</p>
					<p>
						<input type="submit">
					</p>
				</form>
			</body>
		</html>
		"""
		
		
		Ok(html,Map("content-type"->"text/html"))
	}
	
	//处理登录
	post("/handle") {
		scentry.authenticate()
		
		if (isAuthenticated) {
			redirect("admin")
		} else {
			redirect("/")
		}
	}
	
	
	//处理登出
	get("/logout") {
		scentry.logout()
		redirect("/")
	}
}
